package com.face.server.service;

import com.face.RespMsg;
import com.face.server.entity.Joined;
import com.face.server.repository.JoinedRepository;
import com.face.server.vo.AffectDate;
import com.util.DateUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;

import static org.springframework.data.mongodb.core.query.Criteria.*;

import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;

@Service
public class AffectDateService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    JoinedRepository joinedRepository;

    public RespMsg groupBy(String input, Date begin, Date end, Pageable pageable) {

        return RespMsg.build(mongoTemplate.aggregate(newAggregation(
                match(where("classBegin").gte(begin).and("classEnd").lte(end).and("className").regex(input)),
                group("className").first("classBegin").as("classBegin")
                        .first("classEnd").as("classEnd").first("className").as("className"),
                match(where("_id").ne(null)),
                skip((long)pageable.getOffset()), limit(pageable.getPageSize()), sort(pageable.getSort())), "joined", AffectDate.class).getMappedResults());
    }

    public RespMsg save(AffectDate affectDate) throws ParseException {
        if (affectDate.getClassBegin() == null) {
            affectDate.setClassBegin(DateUtils.parse("0000-00-00"));
        }
        if (affectDate.getClassEnd() == null) {
            affectDate.setClassEnd(DateUtils.parse("9999-99-99"));
        }
        mongoTemplate.updateMulti(
                Query.query(where("className").is(affectDate.getClassName())),
                new Update().set("classBegin", affectDate.getClassBegin()).set("classEnd", affectDate.getClassEnd()),
                "joined"
        );
        return RespMsg.build("更新成功");
    }

    public RespMsg delete(String[] classNames) throws ParseException {
        mongoTemplate.updateMulti(
                Query.query(where("className").in(classNames)),
                new Update().set("classBegin", DateUtils.parse("0000-00-00")).set("classEnd", DateUtils.parse("9999-99-99")),
                "joined"
        );
        return RespMsg.build("删除成功");
    }
}


